<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>投票结果展示</title>
<link type="text/css" rel="stylesheet" href="css/style.css" />
	<script src="http://47.106.66.89:8080/js/vue.min.js"></script>
	<script src="http://47.106.66.89:8080/js/axios.min.js"></script>

	<link href="http://47.106.66.89:8080/js/ele-2.15.7/theme-chalk/index.css" rel="stylesheet">
	<script src="http://47.106.66.89:8080/js/ele-2.15.7/index.js"></script>
	<script src="js/vote.js"></script>
</head>
<body>
<div id="app">
	<vote>
		<div id="vote" class="wrap">
			<h2>查看投票</h2>
			<ul class="list">
				<li>
					<h4>{{ voteTitle }}</h4>
					<p class="info">共有 {{ voteOptions.length }} 个选项，已有 {{ totalVotes }} 个网友参与了投票。</p>
					<ol>
						<li v-for="option in voteOptions" :key="option.id" class="vote-option">
							{{ option.name }}
							<div class="rate">
								<div class="ratebg">
									<div class="percent" :style="{ width: option.percentage + '%' }" :class="{ 'animated': isAnimating }"></div>
								</div>
								<p>{{ option.votes }}票<span>({{ option.percentage }}%)</span></p>
							</div>
						</li>
					</ol>
					<div class="goback"><a href="index.html">返回投票列表</a></div>
				</li>
			</ul>
		</div>
		<div class="wrap">
		</div>
	</vote>
</div>
<script>
	let app = new Vue({
		el: '#app',
		data: {
			voteTitle: '最佳编程语言',
			voteOptions: [
				{ id: 1, name: 'Java', votes: 0, percentage: 0 },
				{ id: 2, name: 'C', votes: 0, percentage: 0 },
				{ id: 3, name: 'C++', votes: 0, percentage: 0 },
				{ id: 4, name: 'JavaScript', votes: 0, percentage: 0 },
				{ id: 5, name: '.NET', votes: 0, percentage: 0 }
			],
			totalVotes: 0,
			isAnimating: false
		},
		mounted() {
			// 初始化加载数据
			this.loadVoteData();
			// 定时更新投票结果
			this.startUpdating();
		},
		methods: {
			loadVoteData() {
				// 获取URL中的投票ID参数
				const urlParams = new URLSearchParams(window.location.search);
				const vid = urlParams.get('id') || 1; // 默认使用ID为1的投票
				
				// 从服务器获取投票结果数据
				fetch('/vote/voteResults?vid=' + vid)
					.then(response => response.json())
					.then(data => {
						if (data.code === 1) {
							// 更新投票标题
							fetch('/vote/findById?id=' + vid)
								.then(res => res.json())
								.then(voteData => {
									if (voteData && voteData.vname) {
										this.voteTitle = voteData.vname;
									}
								});
								
								// 更新选项数据
								const results = data.data.results;
								this.voteOptions = results.map((item, index) => ({
									id: index + 1, // 为每个选项添加唯一ID
									name: item.optionName,
									votes: item.votes,
									percentage: 0
								}));
								
								this.totalVotes = data.data.totalVotes;
								this.calculateResults();
						}
					})
					.catch(error => {
						console.error('获取投票数据失败:', error);
					});
			},
			startUpdating() {
				// 每5秒更新一次投票结果
				setInterval(() => {
					this.updateVoteResults();
				}, 5000);
			},
			updateVoteResults() {
				this.isAnimating = true;

				// 获取URL中的投票ID参数
				const urlParams = new URLSearchParams(window.location.search);
				const vid = urlParams.get('id') || 1; // 默认使用ID为1的投票

				// 从服务器获取最新的投票结果数据
				fetch('/vote/voteResults?vid=' + vid)
					.then(response => response.json())
					.then(data => {
						if (data.code === 1) {
							const results = data.data.results;

							// 创建一个临时对象来存储现有选项
							const existingOptions = {};
							this.voteOptions.forEach(option => {
								existingOptions[option.name] = option;
							});

							// 创建新的选项列表
							const updatedOptions = [];
							let maxId = 0;

							// 首先处理所有从服务器返回的选项
							results.forEach((item, index) => {
								if (existingOptions[item.optionName]) {
									// 如果选项已存在，更新票数
									const option = existingOptions[item.optionName];
									option.votes = item.votes;
									updatedOptions.push(option);
									maxId = Math.max(maxId, option.id);
									delete existingOptions[item.optionName]; // 从现有选项中删除已处理的选项
								} else {
									// 如果是新选项，添加到列表中
									maxId++;
									updatedOptions.push({
										id: maxId,
										name: item.optionName,
										votes: item.votes,
										percentage: 0
									});
								}
							});

							// 保留可能未在服务器结果中出现的选项（票数为0）
							for (const name in existingOptions) {
								const option = existingOptions[name];
								option.votes = 0;
								updatedOptions.push(option);
							}

							// 更新选项列表
							this.voteOptions = updatedOptions;
							this.totalVotes = data.data.totalVotes;
							this.calculateResults();

							// 动画结束后重置标记
							setTimeout(() => {
								this.isAnimating = false;
							}, 1000);
						}
					})
					.catch(error => {
							console.error('更新投票数据失败:', error);
						});
			},
			calculateResults() {
				// 计算每个选项的百分比
				this.voteOptions.forEach(option => {
					option.percentage = this.totalVotes > 0 ? Math.round((option.votes / this.totalVotes) * 100) : 0;
				});
				
				// 按票数降序排序
				this.voteOptions.sort((a, b) => b.votes - a.votes);
			}
		}
	});
</script>

</body>
</html>
